package com.info.zhiduoduo.admin.service;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.admin.model.formbean.project.ProjectListFormBean;
import com.info.zhiduoduo.admin.model.formbean.system.BusinessManagerFormBean;
import com.info.zhiduoduo.common.utils.EasyExcelUtil;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.repository.dto.account.ExportBusinessManagerDto;
import com.info.zhiduoduo.repository.dto.account.NumberOfEnterprisesDto;
import com.info.zhiduoduo.repository.dto.foreign.ExportForeignProjectDto;
import com.info.zhiduoduo.repository.dto.project.ProjectBriefDto;
import com.info.zhiduoduo.repository.dto.system.QueryBusinessManagerDto;
import com.info.zhiduoduo.admin.model.formbean.system.SaveBusinessManagerFormBean;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.repository.entity.crm.CrmSystemManager;
import com.info.zhiduoduo.repository.entity.system.BusinessManager;
import com.info.zhiduoduo.repository.mapper.system.BusinessManagerMapper;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Service
public class BusinessManagerService extends BaseService {

    @Autowired
    BusinessManagerMapper businessManagerMapper;

    /**
     * 添加商务经理
     *
     * @param formBean
     * @return
     */
    public SmartResult saveBusinessManager(BaseSimpleFormBean<SaveBusinessManagerFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        SaveBusinessManagerFormBean reqdata = formBean.getReqdata();
        if (null == reqdata || StringUtil.isEmpty(reqdata.getBusinessManager())) {
            return errorParamSmartResult();
        }
        int count = businessManagerMapper.checkBusinessManager(reqdata.getBusinessManager());
        if (count > 0) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            smartResult.setMsg("商务经理已存在");
            return smartResult;
        }
        BusinessManager businessManager = new BusinessManager();
        BeanUtils.copyProperties(reqdata, businessManager);
        if (!businessManager.insert()) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            return smartResult;
        }
        //同时往 CRM那边插入一条数据
        CrmSystemManager crmSystemManager = new CrmSystemManager();
        crmSystemManager.setLoginname(businessManager.getBusinessManager());
        crmSystemManager.setManagername(businessManager.getNickname());
        crmSystemManager.setPassword(MD5Pwd(businessManager.getBusinessManager(), "123456"));
        crmSystemManager.setRoleid(4);
        crmSystemManager.setState(1);
        crmSystemManager.setBusinessManagerId(businessManager.getBusinessManagerId());
        if (!crmSystemManager.insert()) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            return smartResult;
        }
        return smartResult;
    }

    /**
     * 修改商务经理
     *
     * @param formBean
     * @return
     */
    public SmartResult updateBusinessManager(BaseSimpleFormBean<BusinessManagerFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        BusinessManagerFormBean reqdata = formBean.getReqdata();
        if (null == reqdata || 0 == reqdata.getBusinessManagerId() || StringUtil.isEmpty(reqdata.getBusinessManager())) {
            return errorParamSmartResult();
        }
        BusinessManager businessManager = new BusinessManager().selectById(reqdata.getBusinessManagerId());
        if (null == businessManager) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            smartResult.setMsg("商务经理不存在");
            return smartResult;
        }
        BeanUtils.copyProperties(reqdata, businessManager);
        if (!businessManager.updateById()) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            return smartResult;
        }
        return smartResult;
    }

    /**
     * 删除商务经理（逻辑删除）
     *
     * @param formBean
     * @return
     */
    public SmartResult delBusinessManager(BaseSimpleFormBean<BusinessManagerFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        BusinessManagerFormBean reqdata = formBean.getReqdata();
        if (null == reqdata || 0 == reqdata.getBusinessManagerId()) {
            return errorParamSmartResult();
        }
        BusinessManager businessManager = new BusinessManager().selectById(reqdata.getBusinessManagerId());
        if (null == businessManager) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            smartResult.setMsg("商务经理不存在");
            return smartResult;
        }
        //判断该商务有无绑定的企业或者合伙人
        List<BusinessManager> businessManagers = businessManagerMapper.judgeBusinessManager(reqdata.getBusinessManagerId());

        if (businessManagers.size() > 0) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            smartResult.setMsg("存在绑定的企业和合伙人，请先解除绑定再删除");
            return smartResult;
        }
        businessManager.setState(2);
        businessManager.setDeleted(1);
        if (!businessManager.updateById()) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            return smartResult;
        }
        return smartResult;
    }

    /**
     * 查询所有的商务经理（带分页）
     *
     * @param formBean
     * @return
     */
    public SmartResult queryBusinessManager(BaseSimpleFormBean<QueryBusinessManagerDto> formBean) {
        Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
        List<BusinessManager> businessManagerList = businessManagerMapper.queryBusinessManagerByState(formBean.getReqdata());
        return smartResult(businessManagerList, page.getTotal(), page.getPages(), page.getPageNum());
    }

    /**
     * 查询所有的商务经理（不带分页）
     *
     * @param formBean
     * @return
     */
    public SmartResult queryAllBusinessManager(BaseSimpleFormBean<QueryBusinessManagerDto> formBean) {
        List<BusinessManager> businessManagerList = businessManagerMapper.queryBusinessManagerByState(formBean.getReqdata());
        return smartResult(businessManagerList);
    }

    private String MD5Pwd(String username, String pwd) {
        // 加密算法MD5
        // salt盐 username + salt
        // 迭代次数
        return new SimpleHash("MD5", pwd, ByteSource.Util.bytes(username + "salt"), 2).toHex();
    }
    public void exportBusinessManager(HttpServletResponse response,Date yearss,String name) {
       List<ExportBusinessManagerDto> list = businessManagerMapper.exportBusinessManager(yearss,name);
        for (ExportBusinessManagerDto io:list){
            //获取企业总数
            Integer compNum = businessManagerMapper.getCompNum(io.getBusinessManagerId(),io.getYears());
                    if (compNum != null){
                        io.setCompNum(compNum);
                    }
            //获取渠道数
            Integer parNum = businessManagerMapper.getParNum(io.getBusinessManagerId(), io.getYears());
                    if (parNum !=null ){
                        io.setParNum(parNum);
                    }
            //获取跟进和拜访的次数
            List<NumberOfEnterprisesDto> Frequency = businessManagerMapper.getFrequency(io.getBusinessManagerId(), io.getYears());
                    if (Frequency != null) {
                        for (NumberOfEnterprisesDto lists : Frequency) {
                            //状态是1的是线下拜访 2是沟通
                            if (lists.getType() == 1) {
                                io.setVisit(lists.getBcNum());
                            } else if (lists.getType() == 2){
                                io.setFollow(lists.getBcNum());
                            }
                        }
                    }

        }

        String file = RandomUtil.createRandomNo( "商务经理统计表", "");
//        EasyExcelUtil.download(response, file, ExportBusinessManagerDto.class, list);
        try {
            EasyExcel.write(getExcelOutPutStream(response, file), ExportBusinessManagerDto.class).sheet("商务经理统计表").doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
